package com.oop.example.gui;

import com.oop.example.data.EntryPOJO;
import com.oop.example.data.HibernateUtil;
import com.oop.example.processing.EntryDisplay;
import com.oop.example.processing.ErrorException;
import com.oop.example.processing.ParseError;
import com.oop.example.processing.Parser;
import com.oop.example.processing.Preparer;
import com.oop.example.processing.ProcessingFactory;
import com.oop.example.processing.TockenMap;
import com.oop.example.processing.WarnException;
import com.oop.example.utils.Utils;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

/**
 *
 * @author -
 */
public class MainDialog extends javax.swing.JFrame {

    private EntryTableModel em = new EntryTableModel();
    private ParsingTask task = new ParsingTask(em);
    private TockenMap tockenMap = new ProcessingFactory().getTockenMap();

    public MainDialog(java.awt.Frame parent, boolean modal) {
        super();
        initComponents();
        xmlTextPaneSrc.setAutoFormat(true);
        jMenuItemExportToDB.addActionListener(new ImportDBListener());
        jMenuItemLablesDict.addActionListener(new LabelDictionaryListener());
        GoToListener goToListener = new GoToListener(jTableEntrys, jSpinnerGoTo);
        jSpinnerGoTo.addChangeListener(goToListener);
        jButtonRefresh.addActionListener(new RefreshListener());
        jTableEntrys.setModel(em);
        jTableEntrys.getSelectionModel().addListSelectionListener(new SelectionListener(jTableEntrys));
        jButtonGoTo.addActionListener(goToListener);
        jMenuItemExit.addActionListener(new ExitListener());
        for (int i = 0; i < em.columns.length; i++) {
            TableColumn column = jTableEntrys.getColumnModel().getColumn(i);
            column.setPreferredWidth(em.colmns_width[i]);
        }
        jButtonRunParsing.addActionListener(new RunParsing());
        jButtonCancel.addActionListener(new CancelParsing());
        jButtonResetParsing.addActionListener(new ResetParsingResults(jTableEntrys));
        jButtonSaveComment.addActionListener(new SaveCommentActionListener(jTableEntrys));
        jComboBoxFilter.setModel(new DefaultComboBoxModel(EStatus.values()));
        jComboBoxFilter.addActionListener(new SetFilterActionListener(jTableEntrys, jComboBoxFilter));
        List<EStatus> asList = new ArrayList<EStatus>();
        for (EStatus st : EStatus.values()) {
            if (st != EStatus.ALL && st != EStatus.PARSED) {
                asList.add(st);
            }
        }
        List<String> tokentsNames = new ArrayList<String>(tockenMap.getFullTockenMap().values());
        Collections.sort(tokentsNames);
        for (String name : tokentsNames) {
            JCheckBox chee = new JCheckBox();
            Integer id = 0;
            for (Integer i : tockenMap.getFullTockenMap().keySet()) {
                if (tockenMap.getFullTockenMap().get(i).equalsIgnoreCase(name)) {
                    id = i;
                    chee.setText(tockenMap.getFullTockenMap().get(id));
                    chee.addActionListener(new EntryElementFilterListener(id, jTableEntrys));
                    jPanelContentTypes.add(chee);
                    break;
                }
            }
        }
        jComboBoxNewStatus.setModel(new DefaultComboBoxModel(asList.toArray()));
        jMenuItemExportBugs.addActionListener(new ExportBugsListener());
        //jTextFieldErrMsg.setVisible(false);
        jMenuItemMainTarget.addActionListener(new ExportLingvoListener());
        jMenuItemLangs.addActionListener(new LangsListener());
        jCheckBoxMenuItem10.addActionListener(new RefreshTableListener(jTableEntrys));
        jMenuItemExportHeaders.addActionListener(new ExportHeadersListener());
        jMenuItemCompare.addActionListener(new HeaderComparerListener());
        jCheckBoxInvert.addActionListener(new RefreshTableListener(jTableEntrys));
        jButtonMarkError.addActionListener(new MarkActionListener(EStatus.ERROR, jTableEntrys));
        jButtonMarkWarn.addActionListener(new MarkActionListener(EStatus.WARN, jTableEntrys));
        jMI_setup.addActionListener(new SettingsDialogListener());
    }

    private class MarkActionListener implements ActionListener {

        private EStatus toMark = EStatus.NEW;
        private JTable table;

        public MarkActionListener(EStatus toMark, JTable table) {
            this.toMark = toMark;
            this.table = table;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (table.getModel() instanceof EntryTableModel) {
                    int first = table.getSelectedRow();
                    EntryTableModel model = (EntryTableModel) table.getModel();
                    if (first >= 0 && first < model.items.size()) {
                        EntryPOJO entry = model.items.get(first);
                        entry.setStatus(toMark.getId());
                        Session openSession = HibernateUtil.getSessionFactory().openSession();
                        Transaction beginTransaction = openSession.beginTransaction();
                        openSession.update(entry);
                        beginTransaction.commit();
                        openSession.close();
                        model.fireTableRowsUpdated(first, first);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
        }
    }

    private class RefreshTableListener implements ActionListener {

        private JTable table;

        public RefreshTableListener(JTable table) {
            this.table = table;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (table.getModel() instanceof EntryTableModel) {
                EntryTableModel model = (EntryTableModel) table.getModel();
                model.refreshItems();
            }
        }
    }

    private class LangsListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new LangsDialog(MainDialog.this);
            dialog.setVisible(true);
        }
    }

    private class SettingsDialogListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new SettingsDialog(MainDialog.this);
            dialog.setVisible(true);
        }
    }

    private class ExportLingvoListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new ExportDialog(MainDialog.this);
            dialog.setVisible(true);
            //new Exporter(new File("Linvo.xml")).export();
        }
    }

    private class ExportHeadersListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new ExportHeaders(MainDialog.this);
            dialog.setVisible(true);
            //new Exporter(new File("Linvo.xml")).export();
        }
    }

    private class HeaderComparerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new HeaderComparer(MainDialog.this);
            dialog.setVisible(true);
            //new Exporter(new File("Linvo.xml")).export();
        }
    }
    //HeaderComparer

    @XmlRootElement
    public static class Bugs {

        public Bugs() {
        }

        public Bugs(List<EntryPOJO> bugs) {
            this.bugs = bugs;
        }
        public List<EntryPOJO> bugs = null;
    }

    private class ExportBugsListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            List<EntryPOJO> bugs = new ArrayList<EntryPOJO>();

            Session openSession = HibernateUtil.getSessionFactory().openSession();
            try {
                Query createQuery = openSession.createQuery("select a from EntryPOJO a where a.Status=" + EStatus.ERROR.getId() + " or a.Status=" + EStatus.WARN.getId());
                List list = createQuery.list();
                if (list != null) {
                    for (Object o : list) {
                        if (o instanceof EntryPOJO) {
                            bugs.add((EntryPOJO) o);
                        }
                    }
                }
                if (!bugs.isEmpty()) {
                    JAXBContext ctx = JAXBContext.newInstance(Bugs.class);
                    Marshaller createMarshaller = ctx.createMarshaller();
                    createMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy");
                    File f = new File("bugs_" + sdf.format(new Date()) + ".xml");
                    createMarshaller.marshal(new Bugs(bugs), f);
                    JOptionPane.showMessageDialog(MainDialog.this, "Заметки (" + bugs.size() + ") выгружены в файл " + f.getAbsolutePath());
                } else {
                    JOptionPane.showMessageDialog(MainDialog.this, "Заметок не обранужено! Экспорт невозможен");
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            } finally {
                openSession.close();
            }
        }
    }

    private class EntryElementFilterListener implements ActionListener {

        private Integer target;
        private JTable table;

        public EntryElementFilterListener(Integer target, JTable table) {
            this.target = target;
            this.table = table;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            if (table.getModel() instanceof EntryTableModel) {
                EntryTableModel model = (EntryTableModel) table.getModel();
                if (e.getSource() instanceof JCheckBox) {
                    if (((JCheckBox) e.getSource()).isSelected()) {
                        model.addEntryElementFilter(target);
                    } else {
                        model.removeEntryElementFilter(target);
                    }
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jTabbedPaneParsing = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextPaneXML = new XmlTextPane();
        jPanel6 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextPaneHTML = new javax.swing.JTextPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextPaneBody = new javax.swing.JTextPane();
        jTextFieldErrMsg = new javax.swing.JTextField();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane8 = new javax.swing.JScrollPane();
        xmlTextPaneSrc = new com.oop.example.gui.XmlTextPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        jTextPaneComment = new javax.swing.JTextPane();
        jPanel4 = new javax.swing.JPanel();
        jComboBoxNewStatus = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButtonSaveComment = new javax.swing.JButton();
        jButtonMarkWarn = new javax.swing.JButton();
        jButtonMarkError = new javax.swing.JButton();
        jPanelMain = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jButtonRefresh = new javax.swing.JButton();
        jSpinnerGoTo = new javax.swing.JSpinner();
        jButtonGoTo = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButtonRunParsing = new javax.swing.JButton();
        jButtonResetParsing = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        jComboBoxFilter = new javax.swing.JComboBox();
        jToolBar2 = new javax.swing.JToolBar();
        jLabelTotalCount = new javax.swing.JLabel();
        jLabelCount = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabelParsed = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jProgressBarParse = new javax.swing.JProgressBar();
        jButtonCancel = new javax.swing.JButton();
        jSplitPane3 = new javax.swing.JSplitPane();
        jPaneleEntryTypes = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        jPanelContentTypes = new javax.swing.JPanel();
        jCheckBoxInvert = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableEntrys = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItemExportBugs = new javax.swing.JMenuItem();
        jMenuItemMainTarget = new javax.swing.JMenuItem();
        jMenuItemExportHeaders = new javax.swing.JMenuItem();
        jMenuItemCompare = new javax.swing.JMenuItem();
        jMenuItemExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItemLablesDict = new javax.swing.JMenuItem();
        jMenuItemLangs = new javax.swing.JMenuItem();
        jMenuItemExportToDB = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jCheckBoxMenuItem10 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItemItalic = new javax.swing.JCheckBoxMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMI_setup = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LingvoNax");

        jSplitPane1.setDividerLocation(600);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Детализация"));

        jSplitPane2.setDividerLocation(200);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jTextPaneXML.setEditable(false);
        jScrollPane5.setViewportView(jTextPaneXML);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPane2.setRightComponent(jPanel5);

        jScrollPane3.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        jTextPaneHTML.setEditable(false);
        jTextPaneHTML.setContentType("text/html"); // NOI18N
        jTextPaneHTML.setToolTipText("Исходник");
        jScrollPane3.setViewportView(jTextPaneHTML);

        jTextPaneBody.setEditable(false);
        jTextPaneBody.setToolTipText("То что идет в парсер для разбора");
        jTextPaneBody.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTextPaneBodyMousePressed(evt);
            }
        });
        jTextPaneBody.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextPaneBodyKeyTyped(evt);
            }
        });
        jScrollPane4.setViewportView(jTextPaneBody);

        jTextFieldErrMsg.setEditable(false);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldErrMsg)
                    .addComponent(jScrollPane4)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldErrMsg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Предобработка", jPanel7);

        jScrollPane8.setViewportView(xmlTextPaneSrc);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Исходный HTML", jPanel8);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );

        jSplitPane2.setLeftComponent(jPanel6);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane2)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane2)
        );

        jTabbedPaneParsing.addTab("Парсинг", jPanel2);

        jScrollPane6.setViewportView(jTextPaneComment);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jComboBoxNewStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("Изменить статус на");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jComboBoxNewStatus, 0, 311, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxNewStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane6)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPaneParsing.addTab("Комментарии", jPanel3);

        jButtonSaveComment.setText("Сохранить");

        jButtonMarkWarn.setBackground(new java.awt.Color(255, 255, 51));
        jButtonMarkWarn.setText("WARN");
        jButtonMarkWarn.setToolTipText("Пометить статью как содержащую подозрения на ошибку");

        jButtonMarkError.setBackground(new java.awt.Color(255, 0, 0));
        jButtonMarkError.setText("ERROR");
        jButtonMarkError.setToolTipText("Пометить статью как ошибочную");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPaneParsing)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonSaveComment, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonMarkError)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonMarkWarn))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jTabbedPaneParsing)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSaveComment)
                    .addComponent(jButtonMarkWarn)
                    .addComponent(jButtonMarkError))
                .addContainerGap())
        );

        jTabbedPaneParsing.getAccessibleContext().setAccessibleName("Парсинг");

        jSplitPane1.setRightComponent(jPanel1);

        jPanelMain.setBorder(javax.swing.BorderFactory.createTitledBorder("Данные"));

        jToolBar1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButtonRefresh.setText("Перечитать из БД");
        jButtonRefresh.setFocusable(false);
        jButtonRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButtonRefresh);

        jSpinnerGoTo.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), null, null, Integer.valueOf(1)));
        jSpinnerGoTo.setToolTipText("Номер строки, к которой необходимо перейти");
        jSpinnerGoTo.setMaximumSize(new java.awt.Dimension(75, 32767));
        jSpinnerGoTo.setPreferredSize(new java.awt.Dimension(50, 20));
        jToolBar1.add(jSpinnerGoTo);

        jButtonGoTo.setText("Перейти");
        jButtonGoTo.setFocusable(false);
        jButtonGoTo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonGoTo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButtonGoTo);
        jToolBar1.add(jSeparator1);

        jButtonRunParsing.setText("Распарсить");
        jButtonRunParsing.setFocusable(false);
        jButtonRunParsing.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonRunParsing.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButtonRunParsing);

        jButtonResetParsing.setText("Очистить");
        jButtonResetParsing.setFocusable(false);
        jButtonResetParsing.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonResetParsing.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButtonResetParsing);
        jToolBar1.add(jSeparator3);

        jComboBoxFilter.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jToolBar1.add(jComboBoxFilter);

        jToolBar2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        jLabelTotalCount.setText("Всего: ");
        jToolBar2.add(jLabelTotalCount);

        jLabelCount.setText("0");
        jToolBar2.add(jLabelCount);

        jLabel1.setText(", обработано: ");
        jToolBar2.add(jLabel1);

        jLabelParsed.setText("0");
        jToolBar2.add(jLabelParsed);
        jToolBar2.add(jSeparator2);
        jToolBar2.add(jProgressBarParse);

        jButtonCancel.setText("Отменить");
        jButtonCancel.setFocusable(false);
        jButtonCancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonCancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButtonCancel);

        jSplitPane3.setDividerLocation(350);
        jSplitPane3.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPaneleEntryTypes.setBorder(javax.swing.BorderFactory.createTitledBorder("Фильтр статей по элементам"));

        jPanelContentTypes.setLayout(new java.awt.GridLayout(0, 3));
        jScrollPane7.setViewportView(jPanelContentTypes);

        jCheckBoxInvert.setText("Инвертировать");

        javax.swing.GroupLayout jPaneleEntryTypesLayout = new javax.swing.GroupLayout(jPaneleEntryTypes);
        jPaneleEntryTypes.setLayout(jPaneleEntryTypesLayout);
        jPaneleEntryTypesLayout.setHorizontalGroup(
            jPaneleEntryTypesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane7)
            .addGroup(jPaneleEntryTypesLayout.createSequentialGroup()
                .addComponent(jCheckBoxInvert)
                .addGap(0, 468, Short.MAX_VALUE))
        );
        jPaneleEntryTypesLayout.setVerticalGroup(
            jPaneleEntryTypesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPaneleEntryTypesLayout.createSequentialGroup()
                .addComponent(jCheckBoxInvert)
                .addGap(6, 6, 6)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE))
        );

        jSplitPane3.setBottomComponent(jPaneleEntryTypes);

        jTableEntrys.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTableEntrys.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(jTableEntrys);

        jSplitPane3.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout jPanelMainLayout = new javax.swing.GroupLayout(jPanelMain);
        jPanelMain.setLayout(jPanelMainLayout);
        jPanelMainLayout.setHorizontalGroup(
            jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jSplitPane3, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanelMainLayout.setVerticalGroup(
            jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelMainLayout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jSplitPane1.setLeftComponent(jPanelMain);

        jMenu1.setText("File");

        jMenuItemExportBugs.setText("Экспорт багов");
        jMenu1.add(jMenuItemExportBugs);

        jMenuItemMainTarget.setText("Экспорт словаря");
        jMenu1.add(jMenuItemMainTarget);

        jMenuItemExportHeaders.setText("Выгрузить заголовки");
        jMenuItemExportHeaders.setEnabled(false);
        jMenu1.add(jMenuItemExportHeaders);

        jMenuItemCompare.setText("Сравнивалка");
        jMenu1.add(jMenuItemCompare);

        jMenuItemExit.setText("Выход");
        jMenu1.add(jMenuItemExit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        jMenuItemLablesDict.setText("Загрузка справочника помет");
        jMenu2.add(jMenuItemLablesDict);

        jMenuItemLangs.setText("Справочник языков");
        jMenu2.add(jMenuItemLangs);

        jMenuItemExportToDB.setText("Загрузка в БД");
        jMenu2.add(jMenuItemExportToDB);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Тестирование");

        jCheckBoxMenuItem10.setText("Показывать не более 10 случайных строк");
        jMenu3.add(jCheckBoxMenuItem10);

        jCheckBoxMenuItemItalic.setText("Поиск курсива");
        jCheckBoxMenuItemItalic.setEnabled(false);
        jMenu3.add(jCheckBoxMenuItemItalic);

        jMenuItem1.setText("Вывести в консоль список заголовков");
        jMenuItem1.setEnabled(false);
        jMenu3.add(jMenuItem1);

        jMenuBar1.add(jMenu3);

        jMenu4.setText("Настройки");

        jMI_setup.setText("Настройки программы");
        jMenu4.add(jMI_setup);

        jMenuBar1.add(jMenu4);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextPaneBodyKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextPaneBodyKeyTyped
        //if (evt.getKeyCode() == KeyEvent.VK_ENTER){
//        String selectedText = jTextPaneBody.getSelectedText();
//        ItalicBold ib = new ItalicBold(null, false);
//        ib.setText(selectedText);
//        ib.setVisible(true);
        //}
    }//GEN-LAST:event_jTextPaneBodyKeyTyped

    private void jTextPaneBodyMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextPaneBodyMousePressed
        //System.out.println(evt.getButton());
        if (MouseEvent.BUTTON3 == evt.getButton()) {
            //System.out.println("");
            String selectedText = jTextPaneBody.getSelectedText();
            ItalicBold ib = new ItalicBold(this, false);
            ib.setText(selectedText);
            ib.setVisible(true);
        }
    }//GEN-LAST:event_jTextPaneBodyMousePressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonGoTo;
    private javax.swing.JButton jButtonMarkError;
    private javax.swing.JButton jButtonMarkWarn;
    private javax.swing.JButton jButtonRefresh;
    private javax.swing.JButton jButtonResetParsing;
    private javax.swing.JButton jButtonRunParsing;
    private javax.swing.JButton jButtonSaveComment;
    private javax.swing.JCheckBox jCheckBoxInvert;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem10;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItemItalic;
    private javax.swing.JComboBox jComboBoxFilter;
    private javax.swing.JComboBox jComboBoxNewStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelCount;
    private javax.swing.JLabel jLabelParsed;
    private javax.swing.JLabel jLabelTotalCount;
    private javax.swing.JMenuItem jMI_setup;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItemCompare;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JMenuItem jMenuItemExportBugs;
    private javax.swing.JMenuItem jMenuItemExportHeaders;
    private javax.swing.JMenuItem jMenuItemExportToDB;
    private javax.swing.JMenuItem jMenuItemLablesDict;
    private javax.swing.JMenuItem jMenuItemLangs;
    private javax.swing.JMenuItem jMenuItemMainTarget;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanelContentTypes;
    private javax.swing.JPanel jPanelMain;
    private javax.swing.JPanel jPaneleEntryTypes;
    private javax.swing.JProgressBar jProgressBarParse;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JSpinner jSpinnerGoTo;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JSplitPane jSplitPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPaneParsing;
    private javax.swing.JTable jTableEntrys;
    private javax.swing.JTextField jTextFieldErrMsg;
    private javax.swing.JTextPane jTextPaneBody;
    private javax.swing.JTextPane jTextPaneComment;
    private javax.swing.JTextPane jTextPaneHTML;
    private javax.swing.JTextPane jTextPaneXML;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private com.oop.example.gui.XmlTextPane xmlTextPaneSrc;
    // End of variables declaration//GEN-END:variables

    private class GoToListener implements ActionListener, ChangeListener {

        private JTable table;
        private JSpinner spinner;

        public GoToListener(JTable table, JSpinner spinner) {
            this.table = table;
            this.spinner = spinner;
        }

        private void goTo() {

            int index = (Integer) spinner.getValue();
            if (table.getRowCount() >= index) {
                index = index - 1;
                table.getSelectionModel().setSelectionInterval(index, index);
                table.scrollRectToVisible(new Rectangle(table.getCellRect(index, 0, true)));
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            goTo();
        }

        @Override
        public void stateChanged(ChangeEvent e) {
            goTo();
        }
    }

    private class SelectionListener implements ListSelectionListener {

        private EntryDisplay diaplay = new ProcessingFactory().getEntryDisplay();
        private JTable table;

        public SelectionListener(JTable table) {
            this.table = table;
        }

        @Override
        public void valueChanged(ListSelectionEvent e) {
            try {
                if (!e.getValueIsAdjusting()) {
                    jTextPaneXML.setText("");
                    if (table.getModel() instanceof EntryTableModel) {
                        int first = table.getSelectedRow();
                        EntryTableModel model = (EntryTableModel) table.getModel();
                        if (first >= 0 && first < model.items.size()) {
                            EntryPOJO entry = model.items.get(first);
                            ProcessingFactory processingFactory = new ProcessingFactory();
                            Preparer preparer = processingFactory.getPreparer();
                            preparer.setSource(entry.getContent());
                            preparer.clean();
                            preparer.markLabels(Utils.getLabelDictionary());

                            xmlTextPaneSrc.setText(entry.getContent());
                            jTextPaneHTML.setText(diaplay.prepateToDisplayInTextField(entry.getContent()));
                            jTextPaneBody.setText(preparer.getString());
                            jTextPaneComment.setText(entry.getComment());
                            Parser parser = processingFactory.getParser();
                            try {
                                parser.setString(preparer.getString());
                                if (!parser.isApplicable()) {
                                    //jTextFieldErrMsg.setVisible(true);
                                    jTextFieldErrMsg.setText(parser.getErrMessage());
                                    if (parser.getErrPosition() >= 0) {
                                        jTextPaneBody.grabFocus();
                                        jTextPaneBody.setSelectionStart(0);
                                        jTextPaneBody.setSelectionEnd(parser.getErrPosition());
                                    }
                                } else {
                                    parser.parse();
                                    jTextPaneXML.setText(parser.asString());
                                    jTextFieldErrMsg.setText("");
                                }
                            } catch (ParseError ex) {
                                //jTextFieldErrMsg.setVisible(true);
                                jTextPaneBody.grabFocus();
                                jTextPaneBody.setSelectionStart(0);
                                jTextPaneBody.setSelectionEnd(ex.getPosition());
                                jTextFieldErrMsg.setText(ex.getMessage());
                            } catch (Exception ex) {
                                ex.printStackTrace(System.out);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
        }
    }

    private class RefreshListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            em.refreshItems();
        }
    }

    private class EntryTableModel extends AbstractTableModel {

        private EntryDisplay diaplay = new ProcessingFactory().getEntryDisplay();
        public final int[] colmns_width = {55, 500, 50};
        public List<EntryPOJO> items = new ArrayList<EntryPOJO>();
        public final String[] columns = {"ID", "HTML", "Status"};
        public final Class[] clazzz = {Integer.class, String.class, String.class};
        public EStatus status = EStatus.ALL;
        private List<Integer> entryElement = new ArrayList<Integer>();

        public List<EntryPOJO> getItems() {
            return items;
        }

        public EStatus getStatus() {
            return status;
        }

        public void setStatus(EStatus status) {
            this.status = status;
            refreshItems();
        }

        public void addEntryElementFilter(Integer ee) {
            entryElement.add(ee);
            refreshItems();
        }

        public void removeEntryElementFilter(Integer ee) {
            entryElement.remove(ee);
            refreshItems();
        }

        public String getEntryTypeFilter(boolean invert) {
            String mask = "";
            if (!entryElement.isEmpty()) {
                Integer[] arr = {};
                mask = tockenMap.creatQueryMask(invert, entryElement.toArray(arr));
                mask = "(" + mask + ")";
            }
            return mask;
        }

        public void refreshItems() {
            int parsedCount = 0;
            boolean show10 = jCheckBoxMenuItem10.isSelected();
            boolean invert = jCheckBoxInvert.isSelected();
            try {
                Session openSession = HibernateUtil.getSessionFactory().openSession();
                Query createQuery = null;
                String mask = getEntryTypeFilter(invert);
                if (status == EStatus.ALL) {
                    mask = mask.isEmpty() ? mask : " where " + mask;
                    createQuery = openSession.createQuery("select a from EntryPOJO a" + mask + " order by a.ID");
                } else {
                    mask = mask.isEmpty() ? mask : " and " + mask;
                    createQuery = openSession.createQuery("select a from EntryPOJO a where a.Status=" + status.getId() + mask + " order by a.ID");
                }
                System.out.println(createQuery.getQueryString());
                List list = createQuery.list();
                items = new ArrayList<EntryPOJO>();

                if (show10) {
                    int max = 10;
                    if (list.size() < max) {
                        max = list.size();
                    }
                    List<Integer> randomIds = new ArrayList<Integer>();
                    for (int i = 0; i < max; i++) {
                        randomIds.add((int) (((double) list.size() - 1) * Math.random()));
                    }
                    Collections.sort(randomIds);
                    for (int randomId : randomIds) {
                        Object o = list.get(randomId);
                        if (o instanceof EntryPOJO) {
                            EntryPOJO pojo = (EntryPOJO) o;
                            items.add(pojo);
                            parsedCount += (pojo.getStatus() == 1 ? 1 : 0);
                        }
                    }
                } else {
                    for (Object o : list) {
                        if (o instanceof EntryPOJO) {
                            EntryPOJO pojo = (EntryPOJO) o;
                            items.add(pojo);
                            parsedCount += (pojo.getStatus() == 1 ? 1 : 0);
                        }
                    }
                }
                jLabelCount.setText("" + items.size());
                jLabelParsed.setText("" + parsedCount);
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            return items.size();
        }

        @Override
        public int getColumnCount() {
            return columns.length;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return columns[columnIndex];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return clazzz[columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res = null;
            EntryPOJO get = items.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    res = get.getID();
                    break;
                case 1:
                    res = diaplay.prepateToDisplayInTable(get.getContent(), EStatus.byID(get.getStatus()));
                    //System.out.println(res);
                    break;
                case 2:
                    res = EStatus.byID(get.getStatus()).getName();
                    break;
            }
            return res;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        }
    }

    private class ImportDBListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            DBLoader dialog = new DBLoader(MainDialog.this);
            dialog.setVisible(true);
        }
    }

    private class LabelDictionaryListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JDialog dialog = new LabelDictionaryLoader(MainDialog.this);
            dialog.setVisible(true);
        }
    }

    private class ExitListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            MainDialog.this.setVisible(false);
            System.exit(0);
        }
    }

    private class CancelParsing implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            task.stop();
            jProgressBarParse.setToolTipText("Парсинг отменен");
        }
    }

    private class RunParsing implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            new Thread(task).start();
        }
    }

    private class ParsingTask implements Runnable {

        //List<String> entrysHeaders = new ArrayList<String>();
        private boolean stop = false;
        private EntryTableModel model;

        public ParsingTask(EntryTableModel model) {
            this.model = model;
        }

        public void stop() {
            stop = true;
        }

        @Override
        public void run() {
            stop = false;
            Session session = HibernateUtil.getSessionFactory().openSession();
            try {
                Transaction transaction = null;
                int procassed = 0;
                int total = model.items.size();
                jProgressBarParse.setMaximum(total);
                Properties lblDict = Utils.getLabelDictionary();
                transaction = session.beginTransaction();
                for (EntryPOJO pojo : model.items) {
                    if (stop) {
                        break;
                    }
                    try {
                        if (pojo.getStatus() == 0) {
                            ProcessingFactory factory = new ProcessingFactory();
                            Preparer preparer = factory.getPreparer();
                            preparer.setSource(pojo.getContent());
                            preparer.clean();
                            preparer.markLabels(lblDict);
                            if (preparer.check()) {
                                Parser parser = factory.getParser();
                                parser.setString(preparer.getString());
                                if (parser.isApplicable()) {
                                    parser.parse();
                                    String filterMask = parser.getTockenMap().getFilterMask();
                                    pojo.setEntryType(filterMask);
                                    pojo.setStatus(EStatus.PARSED.getId());
                                    session.update(pojo);
                                    model.fireTableRowsUpdated(procassed, procassed);
                                }
                            }
                        }
                    } catch (WarnException ex) {
                        pojo.setComment(ex.getMessage());
                        pojo.setStatus(EStatus.WARN.getId());
                        session.update(pojo);
                        model.fireTableRowsUpdated(procassed, procassed);
                    } catch (ErrorException ex) {
                        pojo.setComment(ex.getMessage());
                        pojo.setStatus(EStatus.ERROR.getId());
                        session.update(pojo);
                        model.fireTableRowsUpdated(procassed, procassed);
                    } catch (Exception ex) {
                        ex.printStackTrace(System.out);
                    }
                    jProgressBarParse.setValue(++procassed);
                    jProgressBarParse.setToolTipText("" + procassed + " из " + total);
                }
                transaction.commit();

            } finally {
                session.close();
            }

            model.refreshItems();
        }
    }

    private class ResetParsingResults implements ActionListener {

        private JTable table;

        public ResetParsingResults(JTable table) {
            this.table = table;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int showConfirmDialog = JOptionPane.showConfirmDialog(MainDialog.this, "Удалить все результаты парсинга?");
            if (showConfirmDialog == JOptionPane.OK_OPTION) {
                Session session = HibernateUtil.getSessionFactory().openSession();
                Transaction beginTransaction = session.beginTransaction();
                try {
                    Query createQuery = session.createQuery("update EntryPOJO a set a.Status = 0, xml='', EntryType='', Comment=''");
                    createQuery.executeUpdate();
                    beginTransaction.commit();
                } catch (Exception ex) {
                    ex.printStackTrace(System.out);
                } finally {
                    session.close();
                }
                if (table.getModel() instanceof EntryTableModel) {
                    ((EntryTableModel) table.getModel()).refreshItems();
                }
            }
        }
    }

    private class SetFilterActionListener implements ActionListener {

        private JTable table;
        private JComboBox cb;

        public SetFilterActionListener(JTable table, JComboBox cb) {
            this.table = table;
            this.cb = cb;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            EStatus st = EStatus.valueOf(cb.getSelectedItem().toString());
            if (table.getModel() instanceof EntryTableModel) {
                EntryTableModel model = (EntryTableModel) table.getModel();
                model.setStatus(st);
            }

        }
    }

    private class SaveCommentActionListener implements ActionListener {

        private JTable table;

        public SaveCommentActionListener(JTable table) {
            this.table = table;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (table.getModel() instanceof EntryTableModel) {
                    int first = table.getSelectedRow();
                    EntryTableModel model = (EntryTableModel) table.getModel();
                    if (first >= 0 && first < model.items.size()) {
                        EntryPOJO entry = model.items.get(first);
                        entry.setComment(jTextPaneComment.getText());
                        EStatus byName = EStatus.valueOf(jComboBoxNewStatus.getSelectedItem().toString());
                        entry.setStatus(byName.getId());
                        entry.setContent(xmlTextPaneSrc.getText());
                        entry.setXml(jTextPaneXML.getText());
                        Session openSession = HibernateUtil.getSessionFactory().openSession();
                        Transaction beginTransaction = openSession.beginTransaction();
                        openSession.update(entry);
                        beginTransaction.commit();
                        openSession.close();
                        model.fireTableRowsUpdated(first, first);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
        }
    }
}
